// 引入mongoose
const mongoose = require("mongoose");
// 引入优惠券模型
const { couponsModel } = require("../db/model/coupons");

// 分页获取优惠券数据
const get = async ({ curPage, eachPage }) => {
  curPage = ~~curPage;
  eachPage = ~~eachPage;
  const data = {
    total: 0,
    maxPage: 0,
    rows: [],
  };
  // 获取当前model映射的集合里面存在的文档总数
  data.total = await couponsModel.countDocuments();
  data.maxPage = Math.ceil(data.total / eachPage);
  // 跳过数据条数
  const skipNum = (curPage - 1) * eachPage;
  // 查询所有数据，并跳过skipnum条，查eachpage条并执行
  data.rows = await couponsModel.find().skip(skipNum).populate("navsId").limit(eachPage).exec();
  return data;
};
//新增优惠券数据
const addCoupon = async ({ name, discount, minMoney, deadLine, navsId }) => {
  const couponsModel = mongoose.model("coupons");
  return await couponsModel.create({
    name,
    discount,
    minMoney,
    deadLine,
    navsId,
  });
};
//删除优惠券
const delCoupon = async (_id) => {
  const couponsModel = mongoose.model("coupons");
  return await couponsModel.deleteOne({ _id });
};
//通过id获取该id对应的优惠券数据
const getOne = async (_id) => {
  const couponsModel = mongoose.model("coupons");
  return await couponsModel.findOne({ _id }).populate("navsId");
};
//通过优惠券id修改优惠券数据
const changeCoupon = async (newData) => {
  const couponsModel = mongoose.model("coupons");
  return await couponsModel.updateOne({ _id: newData._id }, newData);
};
//查询优惠券
const searchCoupon = async (data) => {
  const couponsModel = mongoose.model("coupons");
  return await couponsModel.find(data);
};
module.exports = {
  get,
  addCoupon,
  delCoupon,
  getOne,
  changeCoupon,
  searchCoupon,
};
